package com.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ydd.constant.MessageConstant;
import com.ydd.dto.PageSysRoleManagementDto;
import com.ydd.dto.SysRoleUpdateDto;
import com.ydd.entity.*;
import com.ydd.mapper.SysMenuMapper;
import com.ydd.mapper.SysRoleMapper;
import com.ydd.mapper.SysRoleMenuMapper;
import com.ydd.mapper.SysUserMapper;
import com.ydd.result.Result;
import com.ydd.service.SysRoleManagementService;
import com.ydd.vo.RoleAuthListVo;
import com.ydd.vo.YddUserPageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class SysRoleManagementServiceImpl implements SysRoleManagementService {

    @Autowired(required = false)
    SysRoleMapper sysRoleMapper;

    @Autowired(required = false)
    SysUserMapper sysUserMapper;

    @Autowired(required = false)
    SysMenuMapper sysMenuMapper;

    @Autowired(required = false)
    SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 角色列表-分页
     *
     * @param dto
     * @return
     */
    @Override
    public Result pageList(PageSysRoleManagementDto dto) {
        //默认值
        if (dto.getPage() == null){
            dto.setPage("1");
        }
        if (dto.getLimit() == null){
            dto.setLimit("5");
        }

        // 创建分页对象
        Page<SysRole> page = new Page<>(Integer.valueOf(dto.getPage()),Integer.valueOf(dto.getLimit()));
        //添加条件判断
        LambdaQueryWrapper<SysRole> yddUserLambdaQueryWrapper = Wrappers.lambdaQuery();
        if (dto.getName() != null && dto.getName() != ""){
            yddUserLambdaQueryWrapper.like(SysRole::getName,dto.getName());
        }

        sysRoleMapper.selectPage(page,yddUserLambdaQueryWrapper);

        //获取总数
        long countL = page.getTotal();
        int count = (int) countL;

        //获取总页数
        long totalPagesL = page.getPages();
        int totalPages = (int) totalPagesL;

        //获取每页数量
        long pageSizeL = page.getSize();
        int pageSize = (int) pageSizeL;

        //获取当前页码
        long currentPageL = page.getCurrent();
        int currentPage = (int) currentPageL;

        //页面数据
        List<SysRole> data = page.getRecords();

        //封装Vo返回
        YddUserPageVo vo = YddUserPageVo.builder()
                .count(count)
                .totalPages(totalPages)
                .pageSize(pageSize)
                .currentPage(currentPage)
                .data(data)
                .build();

        return Result.success(vo);

    }

    /**
     * 角色详情
     *
     * @param id
     * @return
     */
    @Override
    public Result roleRowInfo(String id) {
        //查询管理员身份信息
        SysRole sysRole = sysRoleMapper.selectById(id);
        //将管理员身份信息拷贝到Vo中
        RoleAuthListVo roleAuthListVo = new RoleAuthListVo();
        BeanUtils.copyProperties(sysRole,roleAuthListVo);


        //查询所有pid,父级编号为0的menu
        //创建条件对象
        LambdaQueryWrapper<SysMenu> sysMenuLambdaQueryWrapper = Wrappers.lambdaQuery();
        sysMenuLambdaQueryWrapper.eq(SysMenu::getPid,0);
        List<SysMenu> sysMenus = sysMenuMapper.selectList(sysMenuLambdaQueryWrapper);
        //新建集合 存储最顶级的下拉框
        List<MenuChildrenList> authList = new ArrayList<>();
        for (SysMenu sysMenu : sysMenus) {
            MenuChildrenList menuChildrenList = new MenuChildrenList();
            BeanUtils.copyProperties(sysMenu,menuChildrenList);
            authList.add(menuChildrenList);
        }


        //创建新集合放二级下拉框集合
        List<MenuChildrenList> children = new ArrayList<>();
        for (MenuChildrenList menuChildrenList : authList) {
            Integer menuId = menuChildrenList.getId();
            //清除过去条件
            sysMenuLambdaQueryWrapper.clear();
            //根据一级下拉框id作为二级下拉框的pid父级编号做为条件查询
            sysMenuLambdaQueryWrapper.eq(SysMenu::getPid,menuId);
            List<SysMenu> sysMenuList = sysMenuMapper.selectList(sysMenuLambdaQueryWrapper);
            for (SysMenu sysMenu : sysMenuList) {
                MenuChildrenList menuChildrenListList = new MenuChildrenList();
                BeanUtils.copyProperties(sysMenu,menuChildrenListList);
                //二级目录添加数据
                children.add(menuChildrenListList);
                menuChildrenList.setChildren(children);
            }
        }

        for (MenuChildrenList child : children) {
            //获取二级目录id
            Integer pidId = child.getId();
            //清除过去条件
            sysMenuLambdaQueryWrapper.clear();
            //根据二级下拉框id作为三级按钮的pid父级编号做为条件查询
            sysMenuLambdaQueryWrapper.eq(SysMenu::getPid,pidId);
            //三级目录数据
            List<SysMenu> sysMenuList = sysMenuMapper.selectList(sysMenuLambdaQueryWrapper);
            //创建集合封装三级按钮
            List<SysMenuThree> sysMenuThreeList = new ArrayList<>();
            for (SysMenu sysMenu : sysMenuList) {
                SysMenuThree sysMenuthree = new SysMenuThree();
                BeanUtils.copyProperties(sysMenu,sysMenuthree);
                sysMenuThreeList.add(sysMenuthree);
            }

            child.setChildren(sysMenuThreeList);
        }

        //把顶级下拉框集合放入Vo中
        roleAuthListVo.setAuthList(authList);


        return Result.success(roleAuthListVo);
    }



    /**
     * 菜单列表-全部
     *
     * @return
     */
    @Override
    public Result allData() {
        //创建roleList集合封装返回数据
        List<RoleList> roleList = new ArrayList<>();

        //查询所有sys_user表数据
        List<SysUser> sysUsers = sysUserMapper.selectList(null);

        //遍历根据role_id
        for (SysUser sysUser : sysUsers) {
            //获取roleId
            String role_id = sysUser.getRoleId();
            String roleId = role_id.substring(2, role_id.length() - 2);
            //根据id获取role
            SysRole sysRole = sysRoleMapper.selectById(roleId);
            //创建RoleList对象封装数据
            RoleList roleListEntity = RoleList.builder()
                    .id(sysUser.getId())
                    .name(sysUser.getName())
                    .description(sysRole.getDescription())
                    .create_date(sysUser.getUpdateDate())
                    .remarks(sysRole.getRemarks())
                    .del_flag(sysRole.getDelFlag())
                    .superadmin(sysRole.getSuperadmin())
                    .default_data(sysRole.getDefaultData())
                    .build();
            roleList.add(roleListEntity);
        }

        return Result.success(roleList);
    }





    /**
     * 角色删除
     *
     * @param id
     * @return
     */
    @Override
    public Result del(String id) {
        if (id == null && id == ""){
            return Result.error(MessageConstant.ID_EXISTS_FOUND);
        }
        sysUserMapper.deleteById(id);
        return Result.success();
    }

    /**
     * 角色修改
     *
     * @param dto
     * @return
     */
    @Override
    public Result update(SysRoleUpdateDto dto) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(dto,sysRole);
        sysRole.setUpdateDate(LocalDateTime.now());
        sysRoleMapper.updateById(sysRole);

        sysRoleMenuMapper.deleteById(sysRole.getId());


        List<Integer> menuids = dto.getMenuids();
        for (Integer menuid : menuids) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(dto.getId());
            sysRoleMenu.setMenuId(menuid.toString());
            sysRoleMenuMapper.insert(sysRoleMenu);
        }

        return Result.success();
    }

    /**
     * @param dto
     * @return
     */
    @Override
    public Result add(SysRoleUpdateDto dto) {

        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(dto,sysRole);
        sysRole.setCreateDate(LocalDateTime.now());
        sysRole.setUpdateDate(LocalDateTime.now());
        sysRole.setDelFlag("0");
        sysRole.setSuperadmin(0);
        sysRole.setDefaultData("1");

        String newId = UUID.randomUUID().toString();
        sysRole.setId(newId);

        sysRoleMapper.insert(sysRole);
        List<Integer> menuids = dto.getMenuids();
        for (Integer menuid : menuids) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(dto.getId());
            sysRoleMenu.setMenuId(menuid.toString());
            sysRoleMenuMapper.insert(sysRoleMenu);
        }

        return Result.success();
    }


}
